import {
  _decorator,
  Component,
  Vec3,
  CircleCollider2D,
  Contact2DType,
  Collider2D,
  IPhysics2DContact,
  RigidBody2D,
  ERigidBody2DType,
  Vec2,
} from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Bullet')
export class Bullet extends Component {
  @property
  speed: number = 0.1;

  private direction: Vec3 = new Vec3(1, 0, 0);

  protected onLoad() {
    const rb = this.getComponent(RigidBody2D);
    if (!rb) return;
    const col = this.getComponent(CircleCollider2D);
    if (col) {
      col.sensor = true; // 不推僵尸
      col.apply();
      col.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    }
  }

  setDirection(dir: Vec3) {
    this.direction = dir.normalize();
  }

  update(dt: number) {
    const rb = this.getComponent(RigidBody2D);
    if (rb) {
      rb.linearVelocity = new Vec2(
        this.direction.x * this.speed / 20,
        0
      );
    }
    this.node.translate(this.direction.clone().multiplyScalar(this.speed * dt));
    if (this.node.worldPosition.x > 2000) this.node.destroy();
  }

  onBeginContact(
    self: Collider2D,
    other: Collider2D,
    contact: IPhysics2DContact | null
  ) {
    if (/Zombie/i.test(other.node.name)) {
      console.log('进入销毁子弹');
      this.node.destroy();
    }
  }
}
